package com.cyf.selfhelppay.service.impl;

import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.cyf.activemq.network.bean.MqBusinessRsp;
import com.cyf.activemq.network.bean.MqGetFeeDescRsp;
import com.cyf.activemq.network.bean.MqGetFeeRsp;
import com.cyf.activemq.service.MqService;
import com.cyf.db.bean.LocalAdminpara;
import com.cyf.db.mapper.LocalAdminparaMapper;
import com.cyf.service.CommonService;
import com.cyf.service.bean.CustomException;
import com.cyf.db.bean.InParking;
import com.cyf.db.bean.Parking;
import com.cyf.db.bean.PayOrder;
import com.cyf.db.mapper.InParkingMapper;
import com.cyf.db.mapper.ParkingMapper;
import com.cyf.db.mapper.PayOrderMapper;
import com.cyf.pay.alipay.service.AlipayService;
import com.cyf.pay.wxpay.bean.WxpayUnifiedOrderRsp;
import com.cyf.pay.wxpay.service.WxpayService;
import com.cyf.selfhelppay.network.bean.*;
import com.cyf.selfhelppay.service.SHPayService;
import com.cyf.util.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;

/**
 * 自助缴费机相关接口实现类
 * Created by cage on 2017/4/15.
 */
@Service
public class SHPayServiceImpl implements SHPayService {

    private static final Logger logger = LoggerFactory.getLogger(SHPayServiceImpl.class);

    @Autowired
    private ParkingMapper parkingMapper;
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private InParkingMapper inParkingMapper;
    @Autowired
    private LocalAdminparaMapper localAdminparaMapper;

    @Autowired
    private AlipayService alipayService;
    @Autowired
    private WxpayService wxpayService;

    @Autowired
    private MqService mqService;
    @Autowired
    private CommonService commonService;

    @Override
    public SHPayGetQrcodeRsp getQrcode(SHPayGetQrcodeReq req) {
        SHPayGetQrcodeRsp rsp = new SHPayGetQrcodeRsp();
        rsp.setResult(SHPayBusinessRsp.FAIL);
        try {
            Parking parking = parkingMapper.getParkingById(req.getParkingId());
            if (parking == null) {
                rsp.setStrError("查询车场失败！");
                return rsp;
            }

            InParking inParking = inParkingMapper.getByPlateAndParkingId(req.getPlate(), req.getParkingId());
            if (inParking == null) {
                rsp.setStrError("查找入场信息失败！");
                return rsp;
            }

            HashMap<String, Object> reqMap = new HashMap<>();
            reqMap.put("token", "cheyifu1qaz2wsx");
            reqMap.put("plate", req.getPlate());
            reqMap.put("parkingId", req.getParkingId());
            reqMap.put("payType", req.getPayWay());
            ObjectMapper objectMapper = ObjectMapperUtils.getObjectMapper();
            String rspJson = HttpsUtil.post("http://open.cheyifu2016.com:8892/openapi/getQrcode", objectMapper.writeValueAsString(reqMap));
            if (StringUtils.isEmpty(rspJson)) {
                rsp.setStrError("获取支付二维码失败！");
                return rsp;
            }
            logger.info("rspJson {}", rspJson);

            HashMap rspMap = objectMapper.readValue(rspJson, HashMap.class);
            logger.info("rspJson {}", rspJson);
            if (!"1".equals(rspMap.get("result").toString())) {
                rsp.setStrError(String.valueOf(rspMap.get("strError")));
                return rsp;
            }

            rsp.setFee((Integer) rspMap.get("fee"));
            String orderNo = String.valueOf(rspMap.get("orderId"));
            Integer orderId = payOrderMapper.getIdByOrderNo(orderNo);
            rsp.setOrderId(orderId);
            rsp.setResult(SHPayBusinessRsp.SUCCESS);
            rsp.setQrcode(String.valueOf(rspMap.get("qrcode")));

            Object endTime = rspMap.get("endTime");
            if (endTime != null) {
                Date endDate = DateUtil.convertSeconds2Date((Integer) endTime);
                Date curDate = new Date();
                if (endDate.getTime() > curDate.getTime()) {
                    rsp.setCountdown(DateUtil.convertDate2Seconds(endDate) - DateUtil.convertDate2Seconds(curDate));
                }
            }
            /*commonService.checkSupportOnlinePay(inParking);

            Date outTime = new Date();
            MqGetFeeRsp mqGetFeeRsp = mqService.getFee(req.getPlate(), parking.getId(), outTime);
            int fee = mqGetFeeRsp.getFee() - mqGetFeeRsp.getCouponFee();
            rsp.setFee(fee);
            if (fee == 0) {
                rsp.setResult(SHPayBusinessRsp.RESULT_FEE_ZERO);
                rsp.setStrError("费用0元，无需支付！");
                return rsp;
            }
            *//*if (mqGetFeeRsp.getFeeDesc() != null) {
                rsp.setFeeDesc(mqGetFeeRsp.getFeeDesc());
            }*//*
            Date curTime = new Date();
            int curUTC = (int) (curTime.getTime() / 1000);
            if (mqGetFeeRsp.getEndTime() != 0 && mqGetFeeRsp.getEndTime() > curUTC) {
                rsp.setCountdown(mqGetFeeRsp.getEndTime() - curUTC);
            }

            String orderNo = PayUtil.getOrderNo(parking.getId(), curTime);

            // 获取二维码码串
            if (req.getPayWay() == SHPayGetQrcodeReq.PAYWAY_ALIPAY) {
                AlipayTradePrecreateResponse alipayTradePrecreateResponse = alipayService.getQrcode(orderNo, (fee * 0.01) + "", "支付停车费");
                if (alipayTradePrecreateResponse == null || !alipayTradePrecreateResponse.isSuccess()) {
                    rsp.setStrError("获取支付宝支付二维码失败！");
                    return rsp;
                }
                rsp.setQrcode(alipayTradePrecreateResponse.getQrCode());
            } else if (req.getPayWay() == SHPayGetQrcodeReq.PAYWAY_WECHAT) {
                WxpayUnifiedOrderRsp wxpayUnifiedOrderRsp = wxpayService.getQrcode(orderNo, fee, req.getReqIp(), "支付停车费");
                if (WxpayUnifiedOrderRsp.FAIL.equals(wxpayUnifiedOrderRsp.getReturn_code()) || WxpayUnifiedOrderRsp.FAIL.equals(wxpayUnifiedOrderRsp.getResult_code())) {
                    rsp.setStrError("获取微信支付二维码失败！");
                    return rsp;
                }
                rsp.setQrcode(wxpayUnifiedOrderRsp.getCode_url());
            } else {
                rsp.setStrError("不支持此种支付方式！");
                return rsp;
            }
            // 订单保存到数据库
            PayOrder payOrder = new PayOrder();
            payOrder.setInfoId(mqGetFeeRsp.getInParkingId());
            payOrder.setInfoType(PayOrder.INFOTYPE_INPARKING);
            payOrder.setFee(fee);
            payOrder.setOrderNo(orderNo);
            payOrder.setTransactionId("0");
            payOrder.setFeeType(PayOrder.FEETYPE_SELF);
            payOrder.setPlate(req.getPlate());
            payOrder.setOutTime(outTime);
            payOrder.setCreatedTime(curTime);
            payOrder.setParkingId(parking.getId());
            payOrder.setTradeType(PayOrder.TRADETYPE_SHPAY);
            if (req.getPayWay() == SHPayGetQrcodeReq.PAYWAY_ALIPAY) {   // 支付宝
                payOrder.setPayWay(PayOrder.PAY_WAY_ALIPAY);
            } else if (req.getPayWay() == SHPayGetQrcodeReq.PAYWAY_WECHAT) {
                payOrder.setPayWay(PayOrder.PAY_WAY_WECHAT);
            }
            payOrder.setPayStatus(PayOrder.PAY_UNKNOWN);
            payOrderMapper.insertPayOrder(payOrder);
            rsp.setOrderId(payOrder.getId());
            rsp.setResult(SHPayBusinessRsp.SUCCESS);*/
        } catch (Exception e) {
            logger.error("服务器异常：{}", e);
            rsp.setStrError("获取费用失败！");
        }
        return rsp;
    }

    @Override
    public SHPayGetParkingInfoResp getCarInInfo(SHPayGetParkingInfoReq req) {
        SHPayGetParkingInfoResp rsp = new SHPayGetParkingInfoResp();
        rsp.setResult(SHPayBusinessRsp.FAIL);
        try {
            Parking parking = parkingMapper.getParkingById(req.getParkingId());
            if (parking == null) {
                rsp.setStrError("查询车场失败！");
                return rsp;
            }
            InParking inParking = inParkingMapper.getByPlate(req.getPlate());
            if (inParking == null) {
                rsp.setStrError("查找入场信息失败！");
                return rsp;
            }
            if (inParking.getParkingId() != req.getParkingId()) {
                rsp.setStrError("车场未进入该车场！");
                return rsp;
            }

            // 是否启用嵌套车场
            LocalAdminpara localAdminpara = localAdminparaMapper.getByParkingIdAndParaKey(parking.getId(), LocalAdminpara.USE_EMBED_PARKING);
            if (localAdminpara == null || StringUtils.isEmpty(localAdminpara.getParaValue())
                    || Integer.parseInt(localAdminpara.getParaValue()) != Parking.ENABLE_EMBED) {
                rsp.setUseEmbed(0);
            } else {
                rsp.setUseEmbed(1);
            }

            // 主车场入口时间
            if (inParking.getPrimaryInTime() != null) {
                rsp.setPrimaryInTime(DateUtil.formatDate(inParking.getPrimaryInTime(), "yyyy-MM-dd HH:mm"));
            }

            // 嵌套车场入口时间
            if (inParking.getSecondaryInTime() != null) {
                rsp.setSecondaryInTime(DateUtil.formatDate(inParking.getSecondaryInTime(), "yyyy-MM-dd HH:mm"));
            }

            // 主车场入口图片

            if (inParking.getPrimaryInImage() != null && inParking.getPrimaryInImage() != 0) {
                String url = "http://open.cheyifu2016.com:8892/openapi/getImage/" + inParking.getParkingId() + "/" + inParking.getPrimaryInImage();
                rsp.setPrimaryInImage(HttpsUtil.downloadImage(url));
            }

//            if (inParking.getImageUrl() != null && !"".equals(inParking.getImageUrl())) {
//                try {
//                    rsp.setPrimaryInImage(FileUtil.convertFile2ByteArray(inParking.getImageUrl()));
//                } catch (IOException e1) {
//                    logger.info("读取主车场入场图片异常：{}", e1.getMessage());
//                }
//            }

            /*// 嵌套车场入口图片
            if (inParking.getSecondaryImageUrl() != null && !"".equals(inParking.getSecondaryImageUrl())) {
                try {
                    rsp.setSecondaryInImage(FileUtil.convertFile2ByteArray(inParking.getSecondaryImageUrl()));
                } catch (IOException e1) {
                    logger.info("读取嵌套车场入场图片异常：{}", e1.getMessage());
                }
            }*/

            // 主车场入口设备名称
            if (inParking.getPrimaryInDeviceName() != null && !"".equals(inParking.getPrimaryInDeviceName())) {
               rsp.setPrimaryInDeviceName(inParking.getPrimaryInDeviceName());
            }

            // 嵌套车场入口设备名称
            if (inParking.getSecondaryInDeviceName() != null && !"".equals(inParking.getSecondaryInDeviceName())) {
                rsp.setSecondaryInDeviceName(inParking.getSecondaryInDeviceName());
            }
            MqGetFeeDescRsp mqGetFeeDescRsp = mqService.getFeeDesc(inParking.getParkingId(), inParking.getLocalInparkingId());
            if (mqGetFeeDescRsp.getResult() == MqBusinessRsp.ERROR) {
                rsp.setStrError("网络超时！");
            }
            rsp.setFeeDesc(mqGetFeeDescRsp.getFeeDesc());
            rsp.setResult(SHPayBusinessRsp.SUCCESS);
            rsp.setCurTime(DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm"));
        } catch (CustomException e) {
            rsp.setStrError(e.getMessage());
        } catch (Exception e) {
            logger.error("服务器异常：{}", e);
            rsp.setStrError("查找入场信息失败！");
        }
        return rsp;
    }
}
